package mapper;

import server.HttpServlet;
import server.Request;
import web.WebApp;
import web.WebApps;

import java.util.ArrayList;
import java.util.HashMap;

public class MappedContext {

    private HashMap<String, MappedWrapper> mappedWrappers = new HashMap<>();	//   "/demo1" --> mappedContext

    public HttpServlet findFirstServlet(Request request) {
        String url = request.getUrl();
        String contextPath = null;
        String urlPath = null;

        try {
            contextPath =  "/" + url.split("/")[1];     // /demo/aaa/bbb --> /demo为contextPath
            urlPath = url.substring(contextPath.length());    // /demo/aaa/bbb --> /aaa/bbb为urlPath
        } catch(Exception e) {

        }


        if (mappedWrappers.containsKey(contextPath)) {
            return mappedWrappers.get(contextPath).findFirstServlet(urlPath);
        }

        return null;
    }

    public MappedContext(String appBase) {
        WebApps webApps = new WebApps(appBase);

        for (WebApp webApp: webApps.getWebApps()) {
            // System.out.println(webApp.getContextPath() + " " + webApp.getAbsoluteAppBase());

            String contextPath = webApp.getContextPath();
            MappedWrapper mappedWrapper = new MappedWrapper(webApp.getAbsoluteAppBase());

            mappedWrappers.put(contextPath, mappedWrapper);
        }
    }
}
